﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AppCommon;
using SyncLib.Client;
using System.Data.SqlClient;
using SyncLib;
using System.Configuration;
using SyncLib.Interface;
using SyncApplication.Business;

namespace SyncApplication.Controls
{
    public partial class Optional : AppCommon.Controls.UserControlBase
    {
        public Optional()
        {
            InitializeComponent();

        }
        public override void Close()
        {
            pUrlEditor.Controls.Clear();
            base.Close();
        }


        private void Optional_Load(object sender, EventArgs e)
        {
            //ckIntergateSecurity.Checked = sb.IntegratedSecurity;


        }

        internal void LoadOption()
        {
            try
            {
                btnTestClient_Click(null, null);
                colorSuccess.SelectedColor = Properties.Settings.Default.SuccessColor;
                colorError.SelectedColor = Properties.Settings.Default.ErrorColor;
                colorWarning.SelectedColor = Properties.Settings.Default.WarningColor;
                txtConnectionString.Text = CommonVariable.SqlConnectionString;
                cbClient.SelectedValue = ConfigurationManager.AppSettings[ClientConst.ClientID];
                ckSharedProxy.Checked = bool.Parse(ConfigurationManager.AppSettings["CreateProxyPerTask"]);
                txtBatchFolder.Text = CommonVariable.SyncFolderBatch;
                ckCleanBatch.Checked = CommonVariable.CleanBatch;
                ckShowMonitor.Checked = bool.Parse(ConfigurationManager.AppSettings["ShowMonitorForm"]);



                bool runModeManual = ConfigurationManager.AppSettings[ClientConst.SK_RundMode] == "Manual";
                if (runModeManual)
                    ckRunManual.Checked = true;
                else
                {
                    ckRunAutomatic.Checked = true;
                    txtInterval.Text = ConfigurationManager.AppSettings[ClientConst.SK_Interval];
                }

                txtServiceUser.Text = CommonVariable.Get("UserName").ToString();
                txtServicePassword.Text = CommonVariable.Get("Password").ToString();

                pUrlEditor.Controls.Clear();
                pUrlEditor.Controls.Add(ClientSyncContext.UrlProvider.Editor);
                ckRunAutomatic_CheckedChanged(null, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void colorSuccess_SelectedColorChanged(object sender, EventArgs e)
        {

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.SuccessColor = colorSuccess.SelectedColor;
            Properties.Settings.Default.ErrorColor = colorError.SelectedColor;
            Properties.Settings.Default.WarningColor = colorWarning.SelectedColor;
            Properties.Settings.Default.Save();


            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
           // config.AppSettings.Settings.Remove(ClientConst.SK_SqlConnectionString);
            config.AppSettings.Settings[ClientConst.SK_SqlConnectionString].Value = txtConnectionString.Text;
            config.AppSettings.Settings[ClientConst.SK_BatchFolder].Value = txtBatchFolder.Text;
            config.AppSettings.Settings[ClientConst.SK_CleanBatch].Value = ckCleanBatch.Checked.ToString();
            config.AppSettings.Settings[ClientConst.SK_RundMode].Value = ckRunAutomatic.Checked ? "Automatic" : "Manual";
            config.AppSettings.Settings[ClientConst.SK_Interval].Value = txtInterval.Text;
            config.AppSettings.Settings[ClientConst.ClientID].Value = cbClient.SelectedValue.ToString();
            config.AppSettings.Settings["CreateProxyPerTask"].Value = ckSharedProxy.Checked ? "False" : "True";
            config.AppSettings.Settings["ShowMonitorForm"].Value = ckShowMonitor.Checked.ToString();
            ClientSyncContext.UrlProvider.Save();
            //object obj = ConfigurationManager.GetSection("appSettings");
            //AppSettingsSection a = obj as AppSettingsSection;
            //a.SectionInformation.ForceSave = true;
            CommonVariable.Add("UserName", txtServiceUser.Text);
            CommonVariable.Add("Password", txtServicePassword.Text);
            config.AppSettings.Settings["TokenSecur"].Value =
                AuthenticationHandle.Encode(txtServiceUser.Text, txtServicePassword.Text, "nothing");
            config.AppSettings.SectionInformation.ForceSave = true;
            
            config.Save();
            ConfigurationManager.RefreshSection("appSettings");

            Program.LoadAppConfig();
        }

        private void txtInterval_ValueChanged(object sender, EventArgs e)
        {
            TimeSpan ts = TimeSpan.FromMinutes(txtInterval.Value);
            string des = "";
            if (ts.Days > 1)
                des = ts.Days.ToString() + " Ngày ";
            if (ts.Hours > 1 || ts.Days > 1)
                des += ts.Hours.ToString() + " Giờ ";

            des += ts.Minutes.ToString() + " Phút/Lần";
            lbIntervalDes.Text = des;
            //balloonTip1.SetBalloonText(txtInterval, des);


        }

        private void txtBatchFolder_ButtonCustomClick(object sender, EventArgs e)
        {
            FolderBrowserDialog f = new FolderBrowserDialog();
            f.ShowDialog();
            if (f.SelectedPath.Length > 0)
                txtBatchFolder.Text = f.SelectedPath;
            f.Dispose();
        }

        private void ckRunAutomatic_CheckedChanged(object sender, EventArgs e)
        {
            txtInterval.Enabled = ckRunAutomatic.Checked;
            ckShowMonitor.Enabled = ckRunAutomatic.Checked;
        }

        private void textBoxX1_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnTestSQL_Click(object sender, EventArgs e)
        {
            SqlConnection connection = null;
            try
            {
                
                connection = new SqlConnection(txtConnectionString.Text);
                connection.Open();
                MessageBox.Show("Chuỗi kết nối hợp lệ", "Ket qua", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (connection != null && connection.State != ConnectionState.Closed)
                    connection.Close();
            }
        }

        private void btnTestClient_Click(object sender, EventArgs e)
        {
            ProxyInfo<ISyncManager> proxy = null;
            try
            {
                proxy = WcfClientUtil.CreateProxy<ISyncManager>();
                cbClient.DataSource = proxy.Channel.GetClientList().Tables[0];                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                if (proxy != null)
                {
                    proxy.ChannelFactory.Close();
                }
            }
        }

        private void pUrlEditor_Paint(object sender, PaintEventArgs e)
        {

        }

        private void ckRunAutomatic_CheckedChanged_1(object sender, EventArgs e)
        {
            ckRunAutomatic_CheckedChanged(sender, e);
        }
    }
}
